package top.yudoge.dogeeditor.config

import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import top.yudoge.dogeeditor.db.api.DataSourceMetaDataApi
import top.yudoge.dogeeditor.db.api.DataSourceVendorEnum
import top.yudoge.dogeeditor.db.datasource.DataSourceManager
import top.yudoge.dogeeditor.db.datasource.HikariCPDataSourceManager
import top.yudoge.dogeeditor.db.objects.DataSourceConfig
import top.yudoge.dogeeditor.db.service.DataSourceMetaDataService

/**
 * This file will be sit in de-database module......!!!!!!!!!!!!! NOT HERE!!!!!!!!!!
 */
@Configuration
class DataSourceDynamicConfig {

    @Bean
    fun dataSourceManager(properties: DataSourcesProperties): DataSourceManager {
        val manager = HikariCPDataSourceManager()
        val configList = properties.dataSources.map {

            val vendor = DataSourceVendorEnum.byVendorName(it.vendor)
                ?: throw IllegalArgumentException("Unknown vendor name: ${it.vendor} for data source: ${it.identifier}")

            DataSourceConfig(
                it.identifier,
                vendor,
                it.url,
                it.username,
                it.password,
                it.extraParams
            )

        }
        manager.register(configList)
        return manager
    }

    @Bean
    fun dataSourceMetaDataApi(dataSourceManager: DataSourceManager): DataSourceMetaDataApi {
        return DataSourceMetaDataService(dataSourceManager)
    }


}